package com.example.cwproject.controller;

import cn.hutool.core.util.StrUtil;
import com.example.cwproject.common.Result;
import com.example.cwproject.entity.User;
import com.example.cwproject.service.EmailService;
import com.example.cwproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Pattern;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    UserService userService;

    @Autowired
    EmailService emailService;

    //登入
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        if(StrUtil.isBlank(user.getEmail())|| StrUtil.isBlank(user.getPassword())){
            return Result.error("数据输入不合法");
        }
        String msg = userService.login(user);
        return Result.success(msg);
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        if(StrUtil.isBlank(user.getUserName())|| StrUtil.isBlank(user.getPassword()) || !Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", user.getEmail())){
            return Result.error("数据输入不合法");
        }
        user = userService.register(user);
        return Result.success(user);
    }


    //先发送邮箱验证码，若未注册则获得验证码
    @GetMapping(value = "/sendEmailCode")
    public Result sendEmailCode(@RequestParam String email) {
        if (!Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", email)){
            return Result.error("邮箱格式不正确");
        }else{
            String verifyCode = emailService.sendEmail(email);
            return Result.success("验证码发送成功,验证码是："+verifyCode);
        }
    }
}
